#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python_learning 
@File ：multi_process_complete_tasks.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2025/2/14 上午9:22 
"""

import random
import sqlite3
import time
from multiprocessing import Process, Queue


# 模拟数据库操作
class DatabaseManager:
	def __init__(self, db_path):
		self.db_path = db_path

	def get_data(self):
		# 模拟从数据库读取数据
		conn = sqlite3.connect(self.db_path)
		cursor = conn.cursor()
		cursor.execute("SELECT * FROM data")
		result = cursor.fetchall()
		conn.close()
		return result

	def update_data(self, key, value):
		# 模拟更新数据库
		conn = sqlite3.connect(self.db_path)
		cursor = conn.cursor()
		cursor.execute(f"UPDATE data SET value = ? WHERE id = ?", (value, key))
		conn.commit()
		conn.close()


# 模拟 TCP 客户端
class TCPClient:
	def send_message(self, message):
		# 模拟发送 TCP 报文
		print(f"Sent TCP message: {message}")
		return f"Response to {message}"


# 数据读取进程
def data_reader(queue, db_path):
	db = DatabaseManager(db_path)
	while True:
		data = db.get_data()
		queue.put(data)
		print("Data read and sent to main process")
		time.sleep(2)  # 模拟数据读取间隔


# 任务处理进程
def task_processor(queue, db_path):
	db = DatabaseManager(db_path)
	tcp = TCPClient()
	while True:
		if not queue.empty():
			task = queue.get()
			if task["type"] == "update_db":
				db.update_data(task["key"], task["value"])
				print(f"Database updated: key={task['key']}, value={task['value']}")
			elif task["type"] == "send_tcp":
				response = tcp.send_message(task["message"])
				print(f"Received response: {response}")
		time.sleep(1)


# 主进程（模拟界面）
def main_process():
	# 配置
	db_path = "example.db"
	data_queue = Queue()
	task_queue = Queue()

	# 初始化数据库
	conn = sqlite3.connect(db_path)
	cursor = conn.cursor()
	cursor.execute("CREATE TABLE IF NOT EXISTS data (id INTEGER PRIMARY KEY, value TEXT)")
	cursor.execute("INSERT OR IGNORE INTO data (id, value) VALUES (1, 'initial')")
	conn.commit()
	conn.close()

	# 启动数据读取进程
	data_reader_process = Process(target=data_reader, args=(data_queue, db_path))
	data_reader_process.start()

	# 启动任务处理进程
	task_processor_process = Process(target=task_processor, args=(task_queue, db_path))
	task_processor_process.start()

	# 主进程模拟界面交互
	print("Main process is running (simulating UI)")
	while True:
		# 模拟用户交互
		if random.randint(0, 5) == 0:
			print("User triggered database update")
			task_queue.put({"type": "update_db", "key": 1, "value": f"Value {time.time()}"})
		elif random.randint(0, 5) == 1:
			print("User triggered TCP message")
			task_queue.put({"type": "send_tcp", "message": f"Hello at {time.time()}"})

		# 检查数据读取
		if not data_queue.empty():
			data = data_queue.get()
			print(f"Received data: {data}")

		time.sleep(1)


if __name__ == "__main__":
	main_process()
